package tableapi

import java.util
import java.util.concurrent.TimeUnit

import bean.SensorReading
import org.apache.flink.api.common.functions.{ReduceFunction, RichFlatMapFunction, RichMapFunction}
import org.apache.flink.api.common.restartstrategy.RestartStrategies
import org.apache.flink.api.common.state._
import org.apache.flink.api.common.time.Time
import org.apache.flink.api.scala._
import org.apache.flink.configuration.Configuration
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.runtime.state.memory.MemoryStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.scala.{DataStream, StreamExecutionEnvironment}
import org.apache.flink.table.api.Table
import org.apache.flink.table.api.scala.StreamTableEnvironment
import org.apache.flink.table.api.scala._
import org.apache.flink.util.Collector

/**
  * @Description: TODO QQ1667847363
  * @author: xiao kun tai
  * @date:2021/11/27 12:14
  */
object Table1_Example {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    env.setParallelism(1)

    //file source
    val inputPath: String = "src/main/resources/sensor.txt"
    val fileStream: DataStream[String] = env.readTextFile(inputPath)

    val socketStream = env.socketTextStream("192.168.88.106", 7777)

    //先转换为特定的类型
    val dataStream: DataStream[SensorReading] = fileStream.map(data => {
      val arr = data.split(",")
      SensorReading(arr(0), arr(1).toLong, arr(2).toDouble)
    })

    //创建表执行环境
    val tableEnv = StreamTableEnvironment.create(env)

    //基于流创建一张表
    val dataTable: Table = tableEnv.fromDataStream(dataStream)

    //调用Table api进行转换
    val resultTable: Table = dataTable
      .select("id,temperature")
      .filter("id=='sensor_1'")
    resultTable.toAppendStream[(String, Double)].print("table api")

    //直接sql实现
    //注册视图
    tableEnv.createTemporaryView("dataTable", dataTable)
    val sql: String = "select id,temperature from dataTable where id='sensor_1'"
    val resultSqlTable: Table = tableEnv.sqlQuery(sql)
    resultSqlTable.toAppendStream[(String, Double)].print("sql api")

    //查看执行计划
    val explaination: String = tableEnv.explain(resultTable)
    println(explaination)

    env.execute("table api example")
  }


}
